package com.xzh.homeliving.commodity.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzh.common.utils.PageUtils;
import com.xzh.common.utils.Query;
import com.xzh.homeliving.commodity.dao.CategoryDao;
import com.xzh.homeliving.commodity.entity.CategoryEntity;
import com.xzh.homeliving.commodity.service.CategoryService;
import com.xzh.homeliving.commodity.vo.Catalog2Vo;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xzh
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        return entities.stream().filter(e -> e.getParentId() == 0).peek(e -> e.setChildrenCategories(getChildrenCategories(e, entities))).sorted(Comparator.comparingInt(a -> (a.getSort() == null ? 0 : a.getSort()))).collect(Collectors.toList());
    }

    private List<CategoryEntity> getChildrenCategories(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream().filter(e -> Objects.equals(e.getParentId(), root.getId())).peek(e -> e.setChildrenCategories(getChildrenCategories(e, all))).sorted(Comparator.comparingInt(a -> (a.getSort() == null ? 0 : a.getSort()))).collect(Collectors.toList());
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public Long[] getCascadedCategoryId(Long id) {
        ArrayList<Long> cascadedCategoryId = new ArrayList<>();
        getParentIds(cascadedCategoryId, id);
        return cascadedCategoryId.toArray(new Long[0]);
    }

    @Override
    public List<CategoryEntity> getFirstLevelCate() {
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_id", 0));
    }

    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        // 1. 先一次性拿到所有分类数据
        List<CategoryEntity> categoryEntityList = this.baseMapper.selectList(null);
        // 2. 得到一级分类
        List<CategoryEntity> firstCategoryList = getParentCid(categoryEntityList, 0L);
        return firstCategoryList.stream().collect(Collectors.toMap(k -> k.getId().toString(), v -> {
            List<Catalog2Vo> catalog2Vos = new ArrayList<>();
            // 3. 得到一级分类下的所有二级分类
            List<CategoryEntity> secondCategoryList = getParentCid(categoryEntityList, v.getId());
            // 遍历二级分类
            if(secondCategoryList != null && !secondCategoryList.isEmpty()) {
                catalog2Vos = secondCategoryList.stream().map((secondCategory) -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getId().toString(), null,  secondCategory.getId().toString(), secondCategory.getName());
                    // 4. 获取三级分类
                    List<CategoryEntity> thirdCategoryList = getParentCid(categoryEntityList, secondCategory.getId());
                    if(thirdCategoryList != null && !thirdCategoryList.isEmpty()) {
                        List<Catalog2Vo.Category3Vo> category3List = thirdCategoryList.stream().map(thirdCategory -> new Catalog2Vo.Category3Vo(secondCategory.getId().toString(), thirdCategory.getId().toString(), thirdCategory.getName())).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(category3List);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
    }

    private void getParentIds(List<Long> cascadedCategoryId, Long id) {
        // 1. 先将id放入到集合中
        cascadedCategoryId.add(0, id);
        // 2. 通过id得到完整的category实体
        CategoryEntity categoryEntity = this.getById(id);
        // 3. 判断 categoryEntity 的 id 是否为 0
        if(categoryEntity.getParentId() != 0) {
            getParentIds(cascadedCategoryId, categoryEntity.getParentId());
        }
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectEntityList, Long parentId) {
        return selectEntityList.stream().filter(item -> item.getParentId().equals(parentId)).collect(Collectors.toList());
    }
}
